package www.dianbaozu.com.ui

import android.content.Intent
import android.net.Uri
import androidx.activity.viewModels
import androidx.navigation.fragment.findNavController
import com.orhanobut.logger.Logger
import dagger.hilt.android.AndroidEntryPoint
import permissions.dispatcher.PermissionRequest
import permissions.dispatcher.ktx.PermissionsRequester
import permissions.dispatcher.ktx.constructPermissionsRequest
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.ActivityProxyBindingImpl
import www.dianbaozu.com.ui.login.LoginFragment
import www.wen.com.common.lib.base.activity.BaseLoadingActivity
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.PermissionRequestEntity
import www.wen.com.common.lib.extension.*
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.util.ActivityManagerUtil
import www.wen.com.common.lib.util.SpUtil


/**
 * 代理启动fragment的Activity
 */
@AndroidEntryPoint
class ProxyActivity : BaseLoadingActivity<ActivityProxyBindingImpl>() {

    /**
     * 记录触发返回键的时间,用于计算时间间隔是否少于2秒，少于退出应用，否则仅做提醒
     */
    private var mExitTime: Long = 0

    /**
     * 第三方权限处理的api
     */
    private lateinit var mPermissionsRequester: PermissionsRequester

    /**
     * 权限统一处理的实体类
     */
    private lateinit var mPermissionRequestEntity: PermissionRequestEntity

    override fun getLayout(): Int = R.layout.activity_proxy

    private val mViewModel by viewModels<ProxyViewModel>()

    override val viewModel: BaseViewModel
        get() = mViewModel

    override fun initialize() {
        addLifecycleOwner()
        jointServer(intent)
        resetStartDestination(R.navigation.navigation, R.id.splashFragment)
    }

    private fun jointServer(intent: Intent) {
        Logger.i("ProxyActivity Last Action =  ${intent.action}  ${intent.dataString}")

        if (Intent.ACTION_VIEW == intent.action || Intent.ACTION_MAIN == intent.action) {
            val uri: Uri? = intent.data
            if (uri != null) {
                val end = uri.toString()
                mViewModel.invitationUrl.value = end.substringAfter("invitation_url=")
                Logger.i("ProxyActivity Last =  ${mViewModel.invitationUrl.value}")
            }
        }
    }

    /**
     * 如果主页正在前台显示连续触发返回键则关闭应用，否则关闭正正在显示的fragment
     */
    override fun onBackPressed() {
        if (isExitNavFragment(MainFragment::class.java)) {
            isExitNavFragment(
                    MainFragment::class.java,
                    isExit = {
                        if (it.isVisible) {
                            if (System.currentTimeMillis() - mExitTime > 2000) {
                                toast(getString(www.wen.com.common.R.string.press_again_to_exit_the_program))
                                mExitTime = System.currentTimeMillis()
                            } else {
                                ActivityManagerUtil.finishAllActivities()
                            }
                        } else {
                            super.onBackPressed()
                        }
                    }
            )
        } else if (isExitNavFragment(LoginFragment::class.java)) {
            isExitNavFragment(LoginFragment::class.java,
                    isExit = {
                        if (it.isVisible) {
                            super.onBackPressed()
                        } else {
                            it.findNavController().navigateUp()
                        }
                    }
            )
        }

    }

    /**
     * 接收消息事件
     */
    private fun addLifecycleOwner() {
        //统一权限处理
        observeObject(KeyHelper.PERMISSION_REQUEST_KEY, this, PermissionRequestEntity::class.java) {
            mPermissionRequestEntity = this
            constructPermissionsRequest(
                    *permissions,
                    onShowRationale = ::onShowRationale,
                    onPermissionDenied = ::onPermissionDenied,
                    onNeverAskAgain = ::onNeverAskAgain,
                    requiresPermission = ::requiresPermission
            ).also {
                mPermissionsRequester = it
                mPermissionsRequester.launch()
            }
        }

        mViewModel.itac.observe(this) { code ->
            val selectCode = mViewModel.areaCodeEntities.value!!.first { it.code == code }
            SpUtil.encode(KeyHelper.MMKV_ITAC, selectCode)
        }
    }

    /**
     * 第一次请求权限时被拒绝时调用,向用户解释为什么需要调用该权限
     */
    private fun onShowRationale(request: PermissionRequest) {
        request.proceed()
    }

    /**
     * 用于标注如果权限请求失败，但是用户没有勾选不再询问的时候执行的方法
     */
    private fun onPermissionDenied() {
        toast(mPermissionRequestEntity.showMsg)
    }

    /**
     * 当用户选中了授权窗口中的不再询问复选框后并拒绝了权限请求时需要调用的方法，一般可以向用户解释为何申请此权限，并根据实际需求决定是否再次弹出权限请求对话框
     */
    private fun onNeverAskAgain() {
        toast(mPermissionRequestEntity.showMsg)
    }

    /**
     * 当用户给予权限时会执行该方法,通知发送方权限已经申请
     */
    private fun requiresPermission() {
        postObject(mPermissionRequestEntity.key, mPermissionRequestEntity)
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        Logger.i("ProxyActivity Last =  onNewIntent = ${intent.dataString}")
        jointServer(intent)
    }


}